<template>
  <section class="component add-queue">
    <el-form :model="model" :rules="rules" ref="add-form" label-width="100px" class="text-left">
      <el-row>
        <el-col :span="9">
          <el-form-item label="客户号" prop="custNo">
            <el-input v-model.trim="model.custNo" style="width: 80%" :disabled="readOnly || lookReadonly" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button class="btncls" @click="queryCustNo()" :disabled="readOnly || lookReadonly">查询</el-button>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户姓名" prop="custName">
            <el-input v-model.trim="model.custName" :maxlength="20" :disabled="readOnly || lookReadonly" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="投诉人类型" prop="complainPersonType">
            <el-select v-model="model.complainPersonType" :disabled="readOnly || lookReadonly" clearable>
              <el-option v-for="{ code, name, index } in $dict.getDictData('ComplainPersonType')" :key="index" :label="name" :value="code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="投诉人姓名" prop="complainPersonName">
            <el-input v-model.trim="model.complainPersonName" :maxlength="11" :disabled="readOnly || lookReadonly" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contractPhone">
            <el-input v-model.trim="model.contractPhone" :maxlength="11" :disabled="readOnly || lookReadonly" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="投诉来源" prop="complainSource">
            <el-select v-model="model.complainSource" :disabled="readOnly || lookReadonly" clearable>
              <el-option v-for="{ code, name, index } in $dict.getDictData('ComplainSource')" :key="index" :label="name" :value="code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="投诉类型" prop="complainType">
            <el-select v-model="model.complainType" :disabled="readOnly || lookReadonly" clearable>
              <el-option v-for="{ code, name, index } in $dict.getDictData('ComplainType')" :key="index" :label="name" :value="code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="投诉模块" prop="complainModule">
            <el-select v-model="model.complainModule" :disabled="readOnly || lookReadonly" clearable @change="disIpt">
              <el-option v-for="{ code, name, index } in $dict.getDictData('ComplainModule')" :key="index" :label="name" :value="code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="9">
          <el-form-item label="投诉人员">
            <el-input v-model.trim="model.complainedPerson" style="width: 80%" :maxlength="20" clearable :disabled="disInput || readOnly || lookReadonly"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button class="btncls" size="mini" @click="queryComplainedPerson()" :disabled="readOnly || lookReadonly">查询</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="跟进情况" prop="followUp">
            <el-input type="textarea" v-model.trim="model.followUp" :rows="4" :maxlength="500" :disabled="readOnly" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="处理状态" prop="complainStatus">
            <el-select v-model="model.complainStatus" :disabled="readOnly" clearable>
              <el-option v-for="{ code, name, index } in $dict.getDictData('ComplainStatus')" :key="index" :label="name" :value="code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="history-table">
        <el-form-item label="历史跟进记录">
          <data-box :data="signHistoryPageList" @onPageChange="refreshSignHistoryData">
            <template slot="columns">
              <el-table-column prop="createdTime" label="时间" :formatter="row => $filter.dateTimeFormat(row.createdTime)" :min-width="$helper.getColumnWidth(3)" show-overflow-tooltip></el-table-column>
              <el-table-column prop="latestHandleNo" label="处理人代号" :min-width="$helper.getColumnWidth(3)" show-overflow-tooltip></el-table-column>
              <el-table-column prop="latestHandleName" label="处理人姓名" show-overflow-tooltip></el-table-column>
              <el-table-column prop="followUp" label="跟进情况" show-overflow-tooltip></el-table-column>
              <el-table-column prop="complainStatus" label="处理进度" :formatter="row => $filter.dictConvert(row.complainStatus, 'ComplainStatus')" show-overflow-tooltip></el-table-column>
            </template>
          </data-box>
        </el-form-item>
      </el-row>
    </el-form>
    <div class="operate-buttons">
      <el-button @click="close" v-if="edit || readOnly">{{edit ? '取消' : '关闭'}}</el-button>
      <el-button @click="close" v-else>取消</el-button>
      <el-button v-if="!readOnly" @click="commit">{{
        edit ? "提交审批" : "确定"
      }}</el-button>
    </div>

    <!--投诉人员查询-->
    <el-dialog title="经办设置" :center="true" :visible.sync="dialog.complainedPersonDialog" width="900px" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
      <add-complainedPerson :selected="selectAgent" :complainModuleId="complainModuleId" :companyNodata="companyNodata" @selectListArr="selectListArr" @close="dialog.complainedPersonDialog = false" :queueType="model.complainedPerson" ref="add-complainedPerson" @deallBtn="deallBtn" @getAgentData="getAgentData"></add-complainedPerson>
    </el-dialog>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Emit, Prop, Watch } from "vue-property-decorator";
import { QueueService } from "~/services/domain-service/queue-manage.service";
import { CaseQueueService } from "~/services/domain-service/case-queue.service";
import { PageService } from "~/utils/page.service";
import { CustomerComplainService } from "../../services/domain-service/customer-complain.service";
import AddComplainedPerson from "~/components/customer-litigation/add-complainedPerson.vue";

@Component({
  components: { AddComplainedPerson }
})
export default class AddQueue extends Vue {
  @Prop() private readOnly;
  @Prop() private edit;
  @Prop() private lookReadonly;
  @Prop() private queueType;
  @Dependencies(QueueService)
  @Dependencies(QueueService)
  private queueService: QueueService;
  @Dependencies(CaseQueueService)
  private caseQueueService: CaseQueueService;
  @Dependencies(PageService)
  private pageSignHistoryService: PageService;
  @Dependencies(CustomerComplainService) private CustomerComplainService: CustomerComplainService;
  @Dependencies(PageService) private pageService: PageService;

  private strategy: any = [];
  private signHistoryList = [];
  private signHistoryPageList = [];
  private selectAgent: any[] = [];
  private complainModuleId: any = "";
  private companyNodata: any = "";
  private dialog: any = {
    complainedPersonDialog: false
  };
  //队列实体
  private model: any = {
    custNo: "",
    custName: "",
    complainPersonType: "SELF",
    complainPersonName: "",
    contractPhone: "",
    complainSource: "",
    complainType: "",
    complainModule: "",
    complainedPerson: "",
    followUp: "",
    complainStatus: "WAIT"
  };
  private disInput: any = false;
  private khMessage = "请输入客户号";
  private tsMessage = "请选择投诉模块";
  //数据校验
  private rules: any = {
    // custNo: [
    //   { required: true, message: "请输入客户号", trigger: "blur" }
    // ],
    // custName: [
    //   { required: true, message: "请输入客户姓名", trigger: "blur" }
    // ],
    complainPersonName: [
      { required: true, message: "请输入投诉人姓名", trigger: "blur" },
      { max: 20, message: "投诉人姓名不能超过20字符", trigger: "blur" }
    ],
    contractPhone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^\+?[0-9][0-9]*$/, message: "联系电话应输入数字", trigger: 'blur' },
      { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: "请输入合法的联系电话", trigger: "blur", },
    ],
    complainSource: [
      { required: true, message: "请选择投诉来源", trigger: ["blur", "change"] }
    ],
    complainType: [
      { required: true, message: "请选择投诉类型", trigger: ["blur", "change"] }
    ],
    followUp: [
      { required: true, message: "请输入跟进情况", trigger: "blur" }
    ],
    complainStatus: [
      { required: true, message: "请选择处理状态", trigger: ["blur", "change"] }
    ],
  };
  @Emit("refreshList") public refreshList () { };
  @Emit("close") public close () {
    this.reset()
  };

  private mounted(){
    console.log('this.$dict',this.$dict.getDictData('ComplainPersonType'));
  }

  private selectListArr (selectListArrList) {
    console.log('selectListArrList', selectListArrList);

    if (this.model.complainModule === "OUTER") {
      if (selectListArrList.length) {
        this.model.complainedPerson = selectListArrList.map(item => item.companyNo || item.companyName).join(',')
        this.companyNodata = selectListArrList.map(item => item.companyNo).join(',')
      }
    } else {
      if (selectListArrList.length) {
        this.model.complainedPerson = selectListArrList.map(item => item.handCode || item.userName).join(',')
        this.companyNodata = selectListArrList.map(item => item.handCode).join(',')
      }
    }
  }

  private queryCustNo () {
    if (this.model.custNo === "" || this.model.custNo === undefined) { return this.$message.error(this.khMessage) }
    const params: any = { "custNo": this.model.custNo }
    this.CustomerComplainService.getCustNameById(params).subscribe(res => {
      this.model.custName = res
      this.$forceUpdate()
    })
  }
  private queryComplainedPerson () {
    if (this.model.complainModule === "" || this.model.complainModule === undefined) { return this.$message.error(this.tsMessage) }
    this.complainModuleId = this.model.complainModule
    const mde = this.model.complainModule
    if (mde === 'SELF' || mde === 'LAWSUIT' || mde === 'OUTER') {
      this.dialog.complainedPersonDialog = true
      this.$nextTick(() => {
        const addComplainedPerson: any = this.$refs["add-complainedPerson"];
        addComplainedPerson.queueIdChange(this.model.complainModule, this.companyNodata)
      })
    } else {
      this.disInput = true
    }
  }

  private queueIdChange (id) {
    return new Promise(reslove => {
      this.signHistoryPageList = []
      const id1: any = { 'id': id }
      this.CustomerComplainService.getCustomerComplainById(id1).subscribe(res => {
        this.model = res
        console.log('model',this.model);
        this.$forceUpdate()
        reslove(true)
      })
      this.refreshSignHistoryData(id)
    })
  }

  private disIpt () {
    const mde = this.model.complainModule
    if (mde === 'SELF' || mde === 'LAWSUIT' || mde === 'OUTER') {
      this.disInput = false
    } else {
      this.disInput = true
      this.model.complainedPerson = ""
    }
  }

  private getAgentData () {
    // this.queueService
    //   .viewHandlerMessage({ queueId: this.queueId })
    //   .subscribe(data => {
    //     // 外包
    //     if(this.queueType === "OUTER"){
    //       this.selectAgent = data.map(item => {
    //         item.id = item.agentId;
    //         item.outOrgName = item.realName;
    //         item.divisionCode = item.handCode;
    //         item.divisionStatus = item.caseSwitch;
    //       });
    //     }
    //     this.selectAgent = data.map(item => {
    //       return {
    //         ...item,
    //         id: item.agentId
    //       };
    //     });
    //     this.dataHandler(this.selectAgent);
    //   });
  }

  private deallBtn (value) {
    // this.selectAgent = value;
    // this.dataHandler(value);
  }

  private closed (val) { // 关闭后同步表格选中数据
    this.dialog.complainedPerson = false
  }

  /**
   * 重置组件
   */
  private reset () {

    // this.model = {}
    const addForm: any = this.$refs["add-form"];
    addForm.resetFields();
    this.signHistoryPageList = []
    this.model.complainedPerson = ''
    this.model.followUp = ''
  }

  private clearSomeInfo(){
    this.model.followUp = ''
  }

  /**
   * 刷新历史跟进记录
   */
  private refreshSignHistoryData (id) {
    const pageIndex = this.pageSignHistoryService.pageIndex;
    const pageSize = this.pageSignHistoryService.pageSize;
    const id1: any = { 'id': id }
    this.CustomerComplainService.getComplainHistoryList(id1).subscribe((data) => {
      this.signHistoryPageList = data
    })
    this.signHistoryPageList = this.signHistoryList.slice(
      (pageIndex - 1) * pageSize,
      pageIndex * pageSize
    );
  }




  /**
   * 提交验证并并与数据库交互
   */
  private commit () {
    const addForm: any = this.$refs["add-form"];
    addForm.validate(valid => {
      if (valid) {
        if (this.model.complainModule === '') { this.model.complainModule = undefined }
        console.log('this.companyNoData', this.companyNodata);

        // this.model.complainedPerson = this.companyNodata
        this.CustomerComplainService.saveComplain(this.model, this.pageService).subscribe(res => {
          const addForm: any = this.$refs["add-form"];
          addForm.resetFields();
          this.refreshList();  // 刷新list
          this.close();
          this.$message.success("保存成功!");


        })
      }
    });
  }

}
</script>

<style lang="less" scoped>
.add-queue-title {
  padding-bottom: 30px;
  padding-left: 30px;
  font-size: 18px;
  font-weight: bold;
}
.agent-box {
  margin-bottom: 22px;
  .text-right {
    text-align: right;
  }
}
.calendar {
  overflow: hidden;
  margin: 0 200px 22px;
  border-top: 1px solid #dcdfe6;
  border-left: 1px solid #dcdfe6;
  .calendarItem {
    float: left;
    width: 10%;
    box-sizing: border-box;
    line-height: 20px;
    text-align: center;
    border-bottom: 1px solid #dcdfe6;
    border-right: 1px solid #dcdfe6;
    &.active {
      background-color: #e4e7ed;
    }
  }
}
.history-table {
  /deep/ .el-pagination .el-select .el-input {
    width: 100px !important;
  }
  /deep/ .el-pagination__editor.el-input {
    width: 50px !important;
  }
}
.inpTextarea {
  width: 505px;
}

.btncls {
  margin-left: -26px;
  padding: 0 20px;
  min-width: 63px;
}
</style>
